<template>
	<el-form
		ref="statusMapRuleFormRef"
		:model="mapRuleForm"
		:rules="mapRuleFormRules"
		size="small"
		label-width="120px">
		<el-form-item label="原始设备类别" prop="sourceDeviceType" class="width-50">
			<el-select v-model="mapRuleForm.sourceDeviceType"
			           filterable placeholder="请选择原始设备类别"
			           class="width-100" @change="sourceDeviceTypeChange">
				<el-option
					v-for="deviceType in deviceTypeData" :key="deviceType._id"
					:label="deviceType.label" :value="deviceType._id"></el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="原始属性" prop="sourceProp" class="width-50">
			<el-select
				v-model="mapRuleForm.sourceProp"
				placeholder="请选择原始属性名称"
				class="width-100"
				@change="sourcePropChange">
				<el-option
					v-for="param in statusParamData" :key="param.paramKey"
					:label="`${param.paramKey} ${param.paramAlias}`" :value="param.paramKey">
					<span>{{param.paramKey}}</span>
					<span class="mar-lft-10 font-color-warning">{{param.paramAlias}}</span>
				</el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="目标设备类别" prop="targetDeviceType" class="width-50">
			<el-select
				v-model="mapRuleForm.targetDeviceType"
				filterable placeholder="请选择目标设备类别" class="width-100">
				<el-option
					v-for="deviceType in deviceTypeData" :key="deviceType._id"
					:label="deviceType.label" :value="deviceType._id"></el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="目标属性" prop="targetProp" class="width-50">
			<el-input v-model="mapRuleForm.targetProp" placeholder="请填写目标属性名称"></el-input>
		</el-form-item>
		<el-form-item label="映射方式" prop="paramMapType">
			<el-radio-group v-model="mapRuleForm.paramMapType">
				<el-radio
					v-for="(mapWay, idx) in commonConfig.commandMapWay" :key="idx"
					:label="mapWay.value">{{mapWay.label}}</el-radio>
			</el-radio-group>
		</el-form-item>
		<el-form-item
			v-if="mapRuleForm.paramMapType === 2"
			prop="field" label="取值范围" class="width-50">
			<el-row>
				<el-col :span="11">
					<el-row>
						<el-col :span="12" class="pad-rgt-5">
							<el-input-number
								v-model="mapRuleForm.paramFieldMap.preMin"
								controls-position="right" class="width-100" />
						</el-col>
						<el-col :span="12" class="pad-rgt-5">
							<el-input-number
								v-model="mapRuleForm.paramFieldMap.preMax"
								controls-position="right" class="width-100" />
						</el-col>
					</el-row>
				</el-col>
				<el-col :span="2" class="text-align-center pad-rgt-5">=></el-col>
				<el-col :span="11">
					<el-row>
						<el-col :span="12" class="pad-rgt-5">
							<el-input-number
								v-model="mapRuleForm.paramFieldMap.postMin"
								controls-position="right" class="width-100" />
						</el-col>
						<el-col :span="12">
							<el-input-number
								v-model="mapRuleForm.paramFieldMap.postMax"
								controls-position="right" class="width-100" />
						</el-col>
					</el-row>
				</el-col>
			</el-row>
		</el-form-item>
		<el-form-item
			v-if="mapRuleForm.paramMapType === 1"
			prop="paramEnumMap" label="枚举映射">
			<el-table :data="mapRuleForm.paramEnumMap" border stripe style="width: 850px">
				<el-table-column prop="key" label="原始枚举">
					<template #default="scope">
						<span>{{scope.row.sourceEnum}}</span>
						<span class="mar-lft font-color-warning">{{scope.row.enumAlias}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="enumDataType" label="数据类型">
					<template #default="scope">
						<el-select v-model="scope.row.enumDataType" placeholder="请选择目标枚举数据类型" class="width-100">
							<el-option
								v-for="dataType in commonConfig.dataType" :key="dataType.value"
								:label="dataType.label" :value="dataType.value"></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="targetEnum" label="目标枚举">
					<template #default="scope">
						<el-input
							v-if="['string', 'hex'].includes(scope.row.enumDataType)"
							v-model="scope.row.targetEnum" placeholder="请输入目标枚举值" class="width-100"/>
						<el-input-number
							v-else-if="['long', 'decimal'].includes(scope.row.enumDataType)"
							v-model="scope.row.targetEnum" placeholder="请填写目标枚举值" class="width-100"/>
						<el-select
							v-else-if="['boolean'].includes(scope.row.enumDataType)"
							v-model="scope.row.targetEnum" class="width-100">
							<el-option label="true" :value="true"></el-option>
							<el-option label="false" :value="false"></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="remarks" label="备注">
					<template #default="scope">
						<el-input v-model="scope.row.remarks" placeholder="请输入枚举备注" class="width-100"/>
					</template>
				</el-table-column>
			</el-table>
		</el-form-item>
	</el-form>
</template>

<script>
	import {commonConfig} from "@/config/common";
	import {commonString, msgCode} from "@/config/string";
	import {messageHandle} from "@/utils";

	export default {
		name: "StatusMapRule",
		props: {
			deviceTypeData: {
				type: Array,
				default: () => {
					return [];
				}
			},
			mapRuleForm: {
				type: Object,
				default: () => {
					return {
						mapRuleType: 'control',
						sourceDeviceType: '',
						sourceProp: '',
						paramMapType: commonConfig.commandMapWay[1].value,
						targetDeviceType: '',
						targetProp: '',
						targetPropInArray: '',
						paramEnumMap: [],
						paramFieldMap: {
							preMin: 0,
							preMax: 100,
							postMin: 0,
							postMax: 100,
						},
						remarks: '',
					};
				}
			}
		},
		data() {
			return {
				commonConfig: commonConfig,
				mapRuleFormRules: {
					mapRuleType: [{required: true, message: '请选择映射规则类型', trigger: 'change'}],
					sourceDeviceType: [{required: true, message: '请选择原始设备类别', trigger: 'change'}],
					sourceProp: [{required: true, message: '请填写原始属性名', trigger: 'blur'}],
					targetDeviceType: [{required: true, message: '请选择目标设备类别', trigger: 'change'}],
					targetProp: [{required: true, message: '请填写目标属性名', trigger: 'blur'}],
					paramMapType: [{required: true, message: '请选择映射类型', trigger: 'change'}],
				},
				statusParamData: [],
			};
		},
		computed: {
			isStatusCommand() {
				const statusCommandType = [
					commonConfig.commandType[1].value,
					commonConfig.commandType[3].value
				];
				return statusCommandType.includes(this.mapRuleForm.mapRuleType);
			},
			paramOptionsInArray() {
				const paramOptions = [];
				this.statusParamData.forEach(param => {
					const {paramKey = ''} = param;
					!paramKey.includes('List') && paramOptions.push(param);
				});
				return paramOptions;
			},
			isArrayParam() {
				const {targetProp = ''} = this.mapRuleForm;
				return this.isStatusCommand && targetProp.includes('List');
			},
		},
		created() {
			this.getGenCommandData();
		},
		methods: {
			getGenCommandData() {
				if (!this.mapRuleForm.sourceDeviceType) return;
				const param = {deviceType: this.mapRuleForm.sourceDeviceType};
				API.genCommand.genCommAll(param).then(result => {
					const {data = []} = result;
					this.statusParamData = [];
					const paramKeys = [];
					data.forEach(genCommand => {
						// 组装所有带有响应参数的命令参数集合
						const {statusParams = []} = genCommand;
						statusParams.forEach(param => {
							const {paramKey = '', enumList = []} = param;
							if (!paramKeys.includes(paramKey)) {
								paramKeys.push(paramKey);
								this.statusParamData.push(param);
							} else {
								// 合并所有的枚举
								if (enumList.length) {
									const existParam = this.statusParamData.find(param => {
										return param.paramKey === paramKey;
									}) || {};
									const {enumList: existEnumList = []} = existParam;
									enumList.forEach(e => {
										if (!existEnumList.find(ee => ee.key === e.key)) {
											existEnumList.push(e);
										}
									});
								}
							}
						});
					});
				}).catch(err => {
				});
			},
			sourcePropChange(sourceProp = '') {
				const {dataType = '', enumList = []} = this.statusParamData.find(param => {
					return param.paramKey === sourceProp;
				}) || {};
				if (enumList.length) {
					this.mapRuleForm.paramEnumMap = enumList.map(en => {
						const {key = '', alias = ''} = en;
						return {
							enumDataType: commonConfig.dataType[0].value,
							sourceEnum: key,
							targetEnum: '',
							enumAlias: alias,
							remarks: ''
						};
					});
					this.mapRuleForm.paramMapType = commonConfig.commandMapWay[1].value;
				} else {
					if (['long', 'decimal'].includes(dataType)) {
						this.mapRuleForm.paramMapType = commonConfig.commandMapWay[3].value;
					} else {
						this.mapRuleForm.paramMapType = commonConfig.commandMapWay[0].value;
					}
				}
				// 对查询和上报命令，需要组装 storeKey.prop 字段作为 mapRuleForm 的 targetProp 字段
				// if (this.isStatusCommand) {
				// 	const targetParam = this.statusParamData.find(p => p.paramKey === sourceProp);
				// 	if (!targetParam.storeKey) {
				// 		this.mapRuleForm.sourceProp = sourceProp;
				// 	} else {
				// 		!this.isArrayParam && (this.mapRuleForm.targetPropInArray = '');
				// 		this.mapRuleForm.sourceProp = `${targetParam.storeKey}.${sourceProp}`;
				// 	}
				// }
			},
			sourcePropInArrayChange(targetPropInArray = '') {
				this.sourcePropChange(this.mapRuleForm.sourceProp);
				this.mapRuleForm.sourceProp = `${this.mapRuleForm.sourceProp}.${targetPropInArray}`;
			},
			sourceDeviceTypeChange(deviceType = '') {
				this.getGenCommandData();
				this.mapRuleForm.targetDeviceType = deviceType;
			},
			formValidate() {
				return new Promise(resolve => {
					this.$refs['statusMapRuleFormRef'].validate(valid => {
						resolve(valid);
					});
				});
			}
		},
	}
</script>

<style scoped lang="less">

</style>